<?php

class Model_Users 
{
    private function prepareConnection()
    {
        if (!isset($this->db))
        {
            $db = Zend_Registry::get("db_main");
            if (!$db->connected) $db->connect();
            $this->db = $db->escoreboar;
        }
    }

    public function saveUser(array $data)
    {
        $this->prepareConnection();

        $data ['created'] = new MongoDate();
        if (!isset($data["oauthid"])) {
            $data ['token'] = md5 ( uniqid ( rand (), 1 ) );
            $data['password'] = hash('sha256', $data['password'], FALSE);
        }

        
        $safe_insert = true;
        return $this->db->users->insert($data, $safe_insert);
    }

    public function updateUser( $username, array $data)
    {
        $this->prepareConnection();
        return $this->db->users->update(array("username" => $username), array('$set' => $data));
    }

    function deleteUser($username)
    {
        $this->prepareConnection();
        $filter = array('username' => $username);
        $this->db->users->remove($filter);
    }

    public function checkUserLogin($email, $password)
    {
        $this->prepareConnection();
        //return $this->db->users->findOne( array('email' =>$email,'password' =>$password, 'active' => 1 ) );
        return $this->db->users->findOne( array('email' =>$email,'password' =>hash("sha256",$password,false)) );
    }

    public function getUserToken($email)
    {
        $this->prepareConnection();
       $user = $this->db->users->findOne( array('email' =>$email), array('token') );
       return $user['token'];
    }

    public function fetchUserByToken($token)
    {
        $this->prepareConnection();
        return $this->db->users->findOne( array('token' =>$token) );
    }

    public function fetchUser($id)
    {
        $this->prepareConnection();
       return $this->db->users->findOne( array('IdUser' =>$id) );
    }

    public function fetchUserByUsername($username)
    {
        $this->prepareConnection();
        return $this->db->users->findOne( array('username' =>$username) );
    }

    public function fetchUserByEmail($email)
    {
        $this->prepareConnection();
        return $this->db->users->findOne( array('email' =>$email) );
    }


    public function fetchUserByOauthid($oauthid)
    {
        $this->prepareConnection();
        $user = $this->db->users->findOne( array('oauthid' =>$oauthid) );
        return $user;
    }
}

